//
//  MenuController.m
//  This file is part of D&D Manager
//
//  Created by Matthew Hutton on 21/03/2007.
//  Copyright 2007 Matthew Hutton.
//
//D&D Manager, a D&D Character and battle management program.
//Copyright (C) 2007, Matthew Hutton
//
//This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License along with this program; if not, write to:
//The Free Software Foundation, Inc.,
//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

#import "MenuController.h"
#import "MyDocument.h"
#import "AbilityChanged.h"

@implementation MenuController
-(id)init{
	[super init];
	NSUserDefaults *userDef=[NSUserDefaults standardUserDefaults];
	if([userDef objectForKey:@"showFriends"]==nil){
		[userDef setBool:YES
				  forKey:@"showFriends"];
	}
	if([userDef objectForKey:@"showEnemies"]==nil){
		[userDef setBool:YES
				  forKey:@"showEnemies"];
	}
	if([userDef objectForKey:@"characterClasses"]==nil){
		[userDef setObject:[NSArray arrayWithObjects:@"Barbarian",@"Bard",@"Cleric",@"Druid",@"Fighter",@"Monk",@"Paladin",@"Ranger",@"Rouge",@"Sorcerer",@"Wizard",nil]
					forKey:@"characterClasses"];
	}
	if([userDef objectForKey:@"domains"]==nil){
		[userDef setObject:[NSArray arrayWithObjects:@"Air", @"Animal", @"Chaos", @"Death", @"Destruction", @"Earth", @"Evil", @"Fire", @"Good", @"Healing", @"Logic", @"Law", @"Luck", @"Magic", @"Plant", @"Protection", @"Strength", @"Sun", @"Travel", @"Trickery", @"War", @"Water",nil]
					forKey:@"domains"];
	}
	if([userDef objectForKey:@"clearLogOnExit"]==nil){
		[userDef setBool:YES
				  forKey:@"clearLogOnExit"];
	}
	[self disableAllButtons];
	//check system version.
	NSAppleScript *script=[[NSAppleScript alloc] initWithSource:@"system version of (system info)"];
	NSDictionary *dict=nil;
	NSString *result=[[script executeAndReturnError:&dict] stringValue];
	if(dict!=nil){
		NSLog(@"dict=%@",dict);
	}
	BOOL badOS=NO;
	BOOL pantherOrWorse=NO;
	double majorVersion=[[result substringToIndex:5] doubleValue];
	if(majorVersion<=10.4){
		if(majorVersion<10.4){
			badOS=YES;
			pantherOrWorse=YES;
		}else if([[result substringFromIndex:5] intValue]<9){
			badOS=YES;
		}
	}
	
	if(badOS){
		NSAppleScript *script;
		if(pantherOrWorse){
			script=[[NSAppleScript alloc] initWithSource:[NSString stringWithFormat:@"tell application \"Finder\"\nactivate\ndisplay dialog \"D&D Manager Requires Mac OS X 10.4 (Tiger) to run, as it requires parts of the operating system introduced in that version. As you are running version %@, please buy a newer version from Apple or your favourite retailer.\"\nend tell",result]];
		}else{
			script=[[NSAppleScript alloc] initWithSource:[NSString stringWithFormat:@"tell application \"Finder\"\nactivate\ndisplay dialog \"D&D Manager Requires version 10.4.9 of Mac OS X to run, as otherwise it will crash on launch. As you are running version %@, please download the latest version of 10.4 from www.apple.com/downloads/ or via software update.\"\nend tell",result]];
		}
		NSDictionary *dict2=nil;
		[script executeAndReturnError:&dict2];
		if(dict2!=nil){
			NSLog(@"dict=%@",dict2);
		}
		[script release];
		[NSApp terminate:nil];
	}	
	return self;
}
-(IBAction)addCharacter:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] addCharBattle:nil];
}
-(IBAction)addNewDomain:(id)sender{
	NSMutableArray *currentDomains=[NSMutableArray arrayWithCapacity:10];
	[currentDomains setArray:[[NSUserDefaults standardUserDefaults] stringArrayForKey:@"domains"]];
	[currentDomains addObject:@"Unnamed domain"];
	[[NSUserDefaults standardUserDefaults] setObject:currentDomains
											  forKey:@"domains"];
	[domainsTable reloadData];
	//reload character class boxes.
	NSArray *docs=[[NSDocumentController sharedDocumentController] documents];
	int i;
	for(i=0;i<[docs count];i++){
		AppController *appCont=[(MyDocument *)[docs objectAtIndex:i] appController];
		[appCont reloadDomainOptions];
	}
}
-(void)addObjectToCheckedDupes:(NSManagedObject *)obj{
	if(checkedDupes==nil){
		checkedDupes=[[NSMutableArray alloc] initWithCapacity:1];
	}
	if(obj!=nil){
		[checkedDupes addObject:obj];
	}
}
-(IBAction)addQuickCharacter:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] addNewQuickCharacter:nil];
}
-(NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender{
	//check if battlescreen is visible.
	NSArray *docs=[[NSDocumentController sharedDocumentController] documents];
	int i;
	for(i=0;i<[docs count];i++){
		MyDocument *myDoc=(MyDocument *)[docs objectAtIndex:i];
		AppController *appCont=[myDoc appController];
		if([[NSUserDefaults standardUserDefaults] boolForKey:@"clearLogOnExit"]){
			[appCont clearLogSheet:self];
		}
		NSWindow *battleScreen=[[appCont battleController] battleScreen];
		if([battleScreen isVisible]){
			[battleScreen performClose:self];
		}
	}
	return YES;
}
-(void)applicationWillFinishLaunching:(NSNotification *)aNotification{
	if(myDocController==nil){
		myDocController=[[MyDocumentController alloc] init];
	}
}
-(IBAction)attack:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] runAttackFromMainScreen:nil];
}
-(void)attackAndSimilarButtonNowOn:(BOOL)shouldBeOn{
	[attackButton setEnabled:shouldBeOn];
	[duplicateButton setEnabled:shouldBeOn];
	[lockButton setEnabled:shouldBeOn];
	if(!shouldBeOn){
		[removeButton setEnabled:NO];
	}
}
-(IBAction)castSpell:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up, and order docs playing up too.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] castSpellFromMainScreen:nil];
}
-(BOOL)checkDupesForObject:(NSManagedObject *)obj{
	return [checkedDupes containsObject:obj];
}
-(void)clearDupesArray{
	[checkedDupes removeAllObjects];
}
-(IBAction)continueBattle:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up, and order docs playing up too.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] continueBattle:nil];
}
-(void)continueBattleNowOn:(BOOL)shouldBeOn{
	[continueBattleButton setEnabled:shouldBeOn];
}
-(void)controlTextDidEndEditing:(NSNotification *)aNotification{
	if([[aNotification object] isEqualTo:domainsTable]){
		NSString *str=[domainsTable  stringValue];
		NSMutableArray *currentDomains=[NSMutableArray arrayWithCapacity:10];
		[currentDomains setArray:[[NSUserDefaults standardUserDefaults] stringArrayForKey:@"domains"]];
		[currentDomains removeObjectAtIndex:[domainsTable selectedRow]];
		[currentDomains addObject:str];
		[currentDomains sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
		[[NSUserDefaults standardUserDefaults] setObject:currentDomains
												  forKey:@"domains"];
		[domainsTable reloadData];
		//reload character class boxes.
		NSArray *docs=[[NSDocumentController sharedDocumentController] documents];
		int i;
		for(i=0;i<[docs count];i++){
			AppController *appCont=[(MyDocument *)[docs objectAtIndex:i] appController];
			[appCont reloadDomainOptions];
		}
		//check which row str is.
		for(i=0;i<[currentDomains count];i++){
			if([[currentDomains objectAtIndex:i] isEqualToString:str]){
				[domainsTable selectRowIndexes:[NSIndexSet indexSetWithIndex:i] byExtendingSelection:NO];
				break;
			}
		}
	}
}
-(void)defaultButtonsNowOn:(BOOL)shouldBeOn{
	//add turning off of dice sheet etc.
	[importButton setEnabled:shouldBeOn];
	[editCharacterClassesButton setEnabled:shouldBeOn];
	[addCharacterButton setEnabled:shouldBeOn];
	[addQuickCharacterButton setEnabled:shouldBeOn];
}
-(void)disableAbsolutelyAllButtons{
	[fileOptionsButton setEnabled:NO];
	[displayLogButton setEnabled:NO];
	[displayDiceButton setEnabled:NO];
	[self disableAllButtons];
}
-(void)disableAllButtons{
	[attackButton setEnabled:NO];
	[castSpellButton setEnabled:NO];
	[continueBattleButton setEnabled:NO];
	[duplicateButton setEnabled:NO];
	[exitBattleButton setEnabled:NO];
	[grantXPButton setEnabled:NO];
	[lockButton setEnabled:NO];
	[removeButton setEnabled:NO];
	[restButton setEnabled:NO];
	[startBattleButton setEnabled:NO];
	[self defaultButtonsNowOn:NO];
}
-(IBAction)displayLogSheet:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up, and order docs playing up too.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] displayLogSheet];
}
-(IBAction)downloadSpells:(id)sender{
	NSURL *url=[NSURL URLWithString:@"http://www.erasersoft.com/main2/Spells%20Project.html"];
	[[NSWorkspace sharedWorkspace] openURL:url];
}
-(IBAction)duplicateCurrentCharacter:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] duplicateCharacter:nil];
}
-(IBAction)editCharacterClasses:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] setUpCharacterClasses]; 
	[[currentDocument appController] displayEditCharacterClassesSheet:nil];
	
}
-(void)enableDiceAndLogButtons{
	//these should be on unless absolutely all buttons should be off.
	[fileOptionsButton setEnabled:YES];
	[displayLogButton setEnabled:YES];
	[displayDiceButton setEnabled:YES];	
}
-(IBAction)exitBattle:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up, and order docs playing up too.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] exitBattle:nil];
}
-(void)exitBattleNowOn:(BOOL)shouldBeOn{
	[exitBattleButton setEnabled:shouldBeOn];
}
-(IBAction)featValueChanged:(id)sender{
	NSArray *allFiles=[[NSDocumentController sharedDocumentController] documents];
	int i;
	for(i=0;i<[allFiles count];i++){
		MyDocument *doc=(MyDocument *)[allFiles objectAtIndex:i];
		NSArray *array=[[[doc appController] characterController] arrangedObjects];
		int j;
		for(j=0;j<[array count];j++){
			[AbilityChanged getNumberOfFeatsForTheCharacter:[array objectAtIndex:j]];
		}
	}
}
-(IBAction)grantXP:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up, and order docs playing up too.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] displayGrantXPsheet:nil];
}
-(IBAction)import:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up, and order docs playing up too.");
			NSBeep();
			return;
		}
	}
	[currentDocument importCharactersFromOtherFiles:nil];
}
-(IBAction)loadDandDLinksPage:(id)sender{
	NSURL *url=[NSURL URLWithString:@"http://www.erasersoft.com/main2/D%26D%20Links.html"];
	[[NSWorkspace sharedWorkspace] openURL:url];
}
-(IBAction)loadWebsite:(id)sender{
	NSURL *url=[NSURL URLWithString:@"http://www.erasersoft.com/main2/Download.html"];
	[[NSWorkspace sharedWorkspace] openURL:url];
}
-(IBAction)lockCharacter:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up, and order docs playing up too.");
			NSBeep();
			return;
		}
	}
	if([lockButton state]==0){
		[lockButton setState:1];
		[removeButton setEnabled:NO];
	}else{
		[lockButton setState:0];
		[removeButton setEnabled:YES];
	}
	[[currentDocument appController] characterLockNowOn:[lockButton state]];
}
-(IBAction)removeCharacter:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up, and order docs playing up too.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] removeCharacter:nil];
}
-(IBAction)removeDomain:(id)sender{
	NSMutableArray *currentDomains=[NSMutableArray arrayWithCapacity:10];
	[currentDomains setArray:[[NSUserDefaults standardUserDefaults] stringArrayForKey:@"domains"]];
	[currentDomains removeObject:[self tableView:domainsTable
					   objectValueForTableColumn:[[domainsTable tableColumns] objectAtIndex:0]
											 row:[domainsTable selectedRow]]];
	[[NSUserDefaults standardUserDefaults] setObject:currentDomains
											  forKey:@"domains"];
	[domainsTable reloadData];
	//reload character class boxes.
	NSArray *docs=[[NSDocumentController sharedDocumentController] documents];
	int i;
	for(i=0;i<[docs count];i++){
		AppController *appCont=[(MyDocument *)[docs objectAtIndex:i] appController];
		[appCont reloadDomainOptions];
	}
}
-(IBAction)rest:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up, and order docs playing up too.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] loadRestScreen:nil];
}
-(void)restAndGrantXPButtonsNowOn:(BOOL)shouldBeOn{
	[grantXPButton setEnabled:shouldBeOn];
	[restButton setEnabled:shouldBeOn];
}
-(IBAction)rollDice:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up, and order docs playing up too.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] displayRollDiceSheet:nil];
}
-(void)setupCharacterLocked:(BOOL)shouldBeOn{
	[lockButton setState:shouldBeOn];
	if([lockButton isEnabled]){
		[removeButton setEnabled:NO];
	}else{
		[removeButton setEnabled:!shouldBeOn];
	}
}
-(IBAction)showFileOptions:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up, and order docs playing up too.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] showFilePreferences:nil];
}
-(IBAction)showPreferences:(id)sender{
	[domainsTable reloadData];
	[preferencesPanel makeKeyAndOrderFront:sender];
}
-(void)spellButtonNowOn:(BOOL)shouldBeOn{
	[castSpellButton setEnabled:shouldBeOn];
}
-(IBAction)startNewBattle:(id)sender{
	MyDocument *currentDocument=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];
	if(currentDocument==nil){
		currentDocument=(MyDocument *)[[NSApp orderedDocuments] objectAtIndex:0];
		if(currentDocument==nil){
			NSLog(@"currentDocument playing up, and order docs playing up too.");
			NSBeep();
			return;
		}
	}
	[[currentDocument appController] startBattle:nil];
}
-(void)startNewBattleNowOn:(BOOL)shouldBeOn{
	[startBattleButton setEnabled:shouldBeOn];
}
-(int)numberOfRowsInTableView:(NSTableView *)aTableView{
	if([aTableView isEqualTo:domainsTable]){
		return [[[NSUserDefaults standardUserDefaults] stringArrayForKey:@"domains"] count];
	}
	return 0;
}
-(id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
		   row:(int)row{
	if([aTableView isEqualTo:domainsTable]){
		return [[[NSUserDefaults standardUserDefaults] stringArrayForKey:@"domains"] objectAtIndex:row];
	}
	return nil;
}
-(void)dealloc{
	if(myDocController!=nil){
		[myDocController release];
	}
	if(checkedDupes!=nil){
		[checkedDupes release];
	}
	[super dealloc];
}
@end

